package utils;

import utils.annotations.SqlSupport;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;


public class JdbcUtil {
    private JdbcUtil() {
    }

    private static Connection connection;

    public static <T> Connection connectByConfig(Class<T> clazz) {
        try {
            if (clazz.isAnnotationPresent(SqlSupport.class)) {
                SqlSupport infoAnno = clazz.getAnnotation(SqlSupport.class);
                Class.forName(infoAnno.DRIVER());
                connection = DriverManager.getConnection(infoAnno.URL(), infoAnno.USERNAME(), infoAnno.PASSWORD());
                connection.setAutoCommit(false);
                var configs = infoAnno.otherConfigs();
                PreparedStatement ps;
                for (String config : configs) {
                    ps = connection.prepareStatement(config);
                    ps.executeUpdate();
                }
            } else {
                System.err.println("annotation '@SqlSupport' needed!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static Connection getConnection() {
        return connection;
    }

    public static <T,I> I getMapper(Class<T> clazz,Class<I> $interface) {
        return (I)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{$interface}, new DatabaseManipulationProxy());
    }

    public static void connect(String url, String username, String password, String[] otherConfigs) {
        try {
            connection = DriverManager.getConnection(url, username, password);
            if (otherConfigs != null) {
                PreparedStatement ps;
                for (String config : otherConfigs) {
                    ps = connection.prepareStatement(config);
                    ps.executeUpdate();
                }
            }
            connection.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}



